package com.zoro.barn.cloud.gateway.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.webflux.ProxyExchange;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class ProxyController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping("/**")
    public Mono<ResponseEntity<byte[]>> proxy(ProxyExchange<byte[]> proxy, ServerHttpRequest request) throws Exception {
        String path = request.getPath().toString();
        if (path.length() > 1) {
            String target = "http:://" + (path.substring(1));
            logger.info("request: path={}, target={}", path, target);
            return proxy.uri(target).get();
        } else {
            return Mono.create(v -> {
                ResponseEntity<byte[]> entity = ResponseEntity.status(404).body(null);
                v.success(entity);
            });
        }
    }
}

